package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entity.User;
import redis.clients.jedis.Jedis;
import service.UserService;
import service.impl.UserServiceImpl;
import utils.JedisUtil;

public class RegisterByPhoneServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	private UserService userService = new UserServiceImpl();
	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String loginName = request.getParameter("login_name");
		String password = request.getParameter("password");
		
		String phone = request.getParameter("phone");
		String code = request.getParameter("code");
		
		
		String key = "register::"+phone;
		Jedis jedis = JedisUtil.getJedis();
		
		if(!jedis.exists(key)){
			response.getWriter().print("验证码错误");
			return;
		}
		
		String value = jedis.get(key);
		
		if (!value.equals(code)) {
			response.getWriter().print("验证码错误");
			return;
		}
		
		jedis.del(key);
		
		JedisUtil.closeJedis(jedis);
		
		User user = new User();
		user.setLoginName(loginName);
		user.setPassword(password);
		user.setStatus(1); //激活状态
		user.setUsername(loginName);
		user.setPhone(phone);
		if(userService.add(user)){
			response.getWriter().print("注册成功！用户名："+loginName+", 密码："+password+",手机："+phone);
		} else {
			response.getWriter().print("注册失败！");
		}
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}
